#!/usr/bin/env bash
set -euo pipefail

# Uninstall and cleanup MongoDB service and files

MONGODB_BASE_DIR="/opt/RadMedical/product/tool/mongodb"
SYSTEMD_UNIT="/etc/systemd/system/mongod.service"
MONGODB_USER="mongod"
MONGODB_GROUP="mongod"

ensure_root() {
	if [[ "${EUID}" -ne 0 ]]; then
		echo "Please run as root."
		exit 1
	fi
}

stop_and_disable_service() {
	if systemctl list-unit-files | grep -q '^mongod\.service'; then
		systemctl stop mongod || true
		systemctl disable mongod || true
	fi
}

remove_unit() {
	if [[ -f "${SYSTEMD_UNIT}" ]]; then
		rm -f "${SYSTEMD_UNIT}"
		systemctl daemon-reload
	fi
}

remove_files() {
	if [[ -d "${MONGODB_BASE_DIR}" ]]; then
		rm -rf "${MONGODB_BASE_DIR}"
	fi
}

remove_user_group() {
	# Only remove if unused
	if id -u "${MONGODB_USER}" >/dev/null 2>&1; then
		userdel "${MONGODB_USER}" || true
	fi
	if getent group "${MONGODB_GROUP}" >/dev/null 2>&1; then
		groupdel "${MONGODB_GROUP}" || true
	fi
}

main() {
	ensure_root
	stop_and_disable_service
	remove_unit
	remove_files
	remove_user_group
	echo "MongoDB service and files removed."
}

main "$@"



